/* eslint-disable react-refresh/only-export-components */
import { useReducer, createContext, useContext, ReactNode, Dispatch } from 'react'

// 定义 Task 接口
export interface Task {
  id: number
  text: string
  done: boolean
}

// 定义 Action 类型
type TaskAction =
  | { type: 'added'; id: number; text: string }
  | { type: 'changed'; task: Task }
  | { type: 'deleted'; id: number }

// 创建带类型的 Context
const TasksContext = createContext<Task[] | null>(null)
const TasksDispatchContext = createContext<Dispatch<TaskAction> | null>(null)

export function useTasks(): Task[] {
  const context = useContext(TasksContext)

  if (context === null) {
    throw new Error('useTasks must be used within a TasksProvider')
  }
  return context
}

export function useTasksDispatch(): Dispatch<TaskAction> {
  const context = useContext(TasksDispatchContext)

  if (context === null) {
    throw new Error('useTasksDispatch must be used within a TasksProvider')
  }
  return context
}

interface TasksProviderProps {
  children: ReactNode
}

export function TasksProvider({ children }: TasksProviderProps) {
  const [tasks, dispatch] = useReducer(tasksReducer, initialTasks)

  return (
    <TasksContext.Provider value={tasks}>
      <TasksDispatchContext.Provider value={dispatch}>{children}</TasksDispatchContext.Provider>
    </TasksContext.Provider>
  )
}

function tasksReducer(tasks: Task[], action: TaskAction): Task[] {
  switch (action.type) {
    case 'added':
      return [...tasks, { id: action.id, text: action.text, done: false }]
    case 'changed':
      return tasks.map(t => (t.id === action.task.id ? action.task : t))
    case 'deleted':
      return tasks.filter(t => t.id !== action.id)
    default:
      throw new Error(`Unknown action type: ${(action as any).type}`)
  }
}

const initialTasks: Task[] = [
  { id: 0, text: "Philosopher's Path", done: true },
  { id: 1, text: 'Visit the temple', done: false },
  { id: 2, text: 'Drink matcha', done: false },
]
